﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WSS.hameduconn.Bases;
using BussinessLogic;
using DataAccess;

namespace WSS.hameduconn
{
    public partial class AdminManage : BasePage
    {
        private static int CurrentPage = 0;
        private static int CurrentSize = 20;
        private static int TotalPages = 0;
        private static int CurrentId = int.MinValue;
        BLAdmin blAdmins;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsAuthenticated || AuthenticateInfo.admin == null)
                Response.Redirect(ResolveUrl("~/Login.aspx"));

            blAdmins = new BLAdmin();
            if (!IsPostBack)
            {
                btnBack.Visible = false;
                memberUsers.Visible = true;
                memberSection.Visible = false;
                divAlert.Visible = false;
                LoadList();
            }

        }

        private void LoadList()
        {
            if (!String.IsNullOrEmpty(Request.QueryString["p"]))
            {
                bool result = int.TryParse(Request.QueryString["p"], out CurrentPage);
                if (result == false)
                {
                    CurrentPage = 0;
                }
                else
                {
                    CurrentPage--;
                }
            }
            var lstAdmin = blAdmins.GetAdmins(CurrentPage, CurrentSize, out TotalPages);
            grdViewMemberHistory.DataSource = lstAdmin;
            grdViewMemberHistory.DataBind();
            divPaging.InnerHtml = RenderPaging(CurrentPage);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            memberUsers.Visible = false;
            memberSection.Visible = true;
            btnBack.Visible = true;
            btnAdd.Visible = false;
            btnRegister.Visible = true;
            btnUpdate.Visible = false;
            divAlert.Visible = false;
            tbPassword.Enabled = true;
            tbConfirmPassword.Enabled = true;
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            memberUsers.Visible = true;
            memberSection.Visible = false;
            btnAdd.Visible = true;
            divAlert.Visible = false;
            btnBack.Visible = false;
            ClearText();
        }

        protected void ibtEdit_Command(object sender, CommandEventArgs e)
        {
            int adId = int.Parse(e.CommandArgument.ToString());
            Admin admin = blAdmins.GetAdmin(adId);
            if (admin != null)
            {
                tbConfirmPassword.Text = new AUEncrypt().Decrypt(admin.Password);
                tbUsername.Text = admin.Username;
                tbFirstName.Text = admin.Firstname;
                tbLastName.Text = admin.Lastname;
                tbPassword.Text = new AUEncrypt().Decrypt(admin.Password);
                tbJob.Text = admin.Jobtitle;

                CurrentId = admin.Id;
                memberSection.Visible = true;
                memberUsers.Visible = false;
                btnAdd.Visible = false;
                btnBack.Visible = true;
                btnRegister.Visible = false;
                btnUpdate.Visible = true;
                divAlert.Visible = false;
            }
            else
            {
                AlertWarning("Error");
                return;
            }
        }

        protected void grdViewMemberHistory_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Admin n = (Admin)e.Row.DataItem;

                Label lblNo = (Label)e.Row.FindControl("lblNo");
                lblNo.Text = Convert.ToString(CurrentPage * CurrentSize + e.Row.RowIndex + 1);
            }
        }

        protected string RenderPaging(int current)
        {
            if (current > TotalPages)
            {
                return "";
            }
            string html = "<ul class=\"pagination\">";

            if (current == 0)
            {
                html +=
                    "<li class=\"first disabled\"><a href=\"#\"><< First</a></li>" +
                        "<li class=\"prev disabled\"><a href=\"#\">< Prev</a></li>";
            }
            else
            {
                html += "<li class=\"first\"><a href=\"" + ResolveUrl("~/AdminManage.aspx?p=" + 1) + "\"><< First</a></li>" +
                        "<li class=\"prev\"><a href=\"" + ResolveUrl("~/AdminManage.aspx?&p=" + current) + "\">< Previous</a></li>";
            }

            for (int i = 1; i <= TotalPages; i++)
            {
                if (current == (i - 1))
                {
                    html += "<li class=\"active\"><a href=\"#\">" + i + "</a></li>";
                }
                else
                {
                    html += "<li><a href='" + ResolveUrl("~/AdminManage.aspx&p=" + i) + "'>" + i + "</a></li>";
                }
            }

            if (current < (TotalPages - 1))
            {
                html += "<li class=\"next\"><a href=\"" + ResolveUrl("~/AdminManage.aspx&p=" + (current + 2)) + "\">Next ></a></li>" +
                        "<li class=\"last\"><a href=\"" + ResolveUrl("~/AdminManage.aspx&p=" + TotalPages) + "\">Last >></a></li>";
            }
            else
            {
                html += "<li class=\"next disabled\"><a href=\"#\">Next ></a></li>" +
                        "<li class=\"last disabled\"><a href=\"#\">Last >></a></li>";
            }
            html += "</ul>";
            return html;
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            string fName = tbFirstName.Text;
            string lName = tbLastName.Text;
            string passWord = tbPassword.Text;
            string confirmPassWord = tbConfirmPassword.Text;
            string username = tbUsername.Text;
            string jobTitle = tbJob.Text;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(passWord) || string.IsNullOrEmpty(confirmPassWord))
            {
                AlertWarning("Please input require field");
                return;
            }

            if (passWord != confirmPassWord)
            {
                AlertWarning("Confirm password incorrect");
                return;
            }

            Admin admin = new Admin
            {
                Username=username,
                Firstname = fName,
                Lastname = lName,
                Jobtitle = jobTitle,
                Password = new AUEncrypt().Encrypt(passWord)
            };

            if (blAdmins.Insert(admin))
            {
                memberSection.Visible = false;
                memberUsers.Visible = true;
                btnAdd.Visible = true;
                LoadList();
                ClearText();
                AlertSuccess("Create admin success !");
            }
            else
            {
                AlertError("Create admin fail!");
            }
        }

        protected void AlertWarning(string msg)
        {
            divAlert.Attributes["class"] = "alert alert-danger";
            divAlert.InnerHtml = msg;
            divAlert.Visible = true;
        }

        protected void AlertError(string msg)
        {
            divAlert.Attributes["class"] = "alert alert-danger";
            divAlert.InnerHtml = msg;
            divAlert.Visible = true;
        }

        protected void AlertSuccess(string msg)
        {
            divAlert.Attributes["class"] = "alert alert-success";
            divAlert.InnerHtml = msg;
            divAlert.Visible = true;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdAmindId.Value) || hdAmindId.Value == "0")
            {
                return;
            }
            int adminId = int.MinValue;
            if (!int.TryParse(hdAmindId.Value, out adminId))
            {
                return;
            }
            if (blAdmins.DeleteAdmin(adminId))
            {
                AlertSuccess("Delete admin success");
                LoadList();
            }
            else
            {
                AlertError("Delete admin fail.");
                return;
            }

        }
        protected void ClearText()
        {
            tbUsername.Text = string.Empty;
            tbConfirmPassword.Text = string.Empty;          
            tbFirstName.Text = string.Empty;
            tbLastName.Text = string.Empty;
            tbPassword.Text = string.Empty;
            tbJob.Text = string.Empty;
            CurrentId = int.MinValue;
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string fName = tbFirstName.Text;
            string lName = tbLastName.Text;
            string passWord = tbPassword.Text;
            string confirmPassWord = tbConfirmPassword.Text;
            string username = tbUsername.Text;
            string jobTitle = tbJob.Text;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(passWord) || string.IsNullOrEmpty(confirmPassWord))
            {
                AlertWarning("Please input require field");
                return;
            }

            if (passWord != confirmPassWord)
            {
                AlertWarning("Confirm password incorrect");
                return;
            }

            Admin admin = new Admin
            {
                Username = username,
                Firstname = fName,
                Lastname = lName,
                Jobtitle = jobTitle,
                Password = new AUEncrypt().Encrypt(passWord),
                Id = CurrentId,
            };
          

            if (blAdmins.Update(admin))
            {
                memberSection.Visible = false;
                memberUsers.Visible = true;
                btnAdd.Visible = true;
                btnBack.Visible = false;
                LoadList();
                AlertSuccess("Update admin profile success !");
            }
            else
            {
                AlertError("Update admin profile fail!");
            }
        }
    }
}